﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using ZXing;
using ZXing.QrCode;
/// <summary>
/// https://cli.im/api?text=//cli.im&mhid=sEqTDAy8z84hMHYrKtRVMaw 在这个网址 选择美化样式 然后复制 mhid= 后面的码 就可以生成美化后的二维码
/// </summary>
public class QrCanvas : MonoBehaviour
{
    public static QrCanvas Instance;
    public GameObject QrShowArea;
    public WebCameraPanel webCameraPanel;
    private void Awake()
    {
        Instance = this;
    }

    IEnumerator GetQrTexture2D(string Text,string QrID,Action<Texture2D> action)
    {
        string url = "https://cli.im/api/qrcode/code?text=" + Text + "&mhid=" + QrID;
        UnityWebRequest request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();
        
        if (request.isHttpError || request.isNetworkError)
        {
            UnityEngine.Debug.Log(request.error+ "当前调取草料二维码失败改成本地生成二维码");
            action(CreateQr(Text,256,256));
        }
        else
        {
            string[] t = request.downloadHandler.text.Split('\n');
            string[] DatStrs = t[2].Split('"');
            UnityWebRequest www = UnityWebRequest.Get(DatStrs[1]);
            yield return www.SendWebRequest();
            byte[] data = www.downloadHandler.data;
            Texture2D temp = BytesToTexture2D(data, 100, 100);
            action(temp);
        }
    }
    public void StartReadQrCode(Action <string>action)
    {
        if (webCameraPanel)
        {
            webCameraPanel.StartReadQrCode(action);
        }
    }

    //定义方法生成二维码  
    private static Color32[] Encode(string textForEncoding, int width, int height)
    {
        var writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new QrCodeEncodingOptions
            {
                Height = height,
                Width = width
            }
        };
        return writer.Write(textForEncoding);
    }

    /// <summary>
    /// 创建二维码
    /// </summary>
    /// <param name="textForEncoding"></param>
    /// <param name="width"></param>
    /// <param name="heights"></param>
    /// <returns></returns>
    public Texture2D CreateQr(string textForEncoding,int width, int heights)
    {
        Texture2D tempTexture = new Texture2D(width, heights);
        var color32 = Encode(textForEncoding,width, heights);
        tempTexture.SetPixels32(color32);
        tempTexture.Apply();
        return tempTexture;
    }
    
    /// <summary>
    /// byte[] 转 Texture2D
    /// </summary>
    /// <param name="data">数据流</param>
    /// <param name="W">长</param>
    /// <param name="H">宽</param>
    /// <returns></returns>
    private Texture2D BytesToTexture2D(byte[] data, int W, int H)
    {
        Texture2D texture2D = new Texture2D(W, H);
        texture2D.LoadImage(data);
        return texture2D;
    }


    public void ShowQr(string Text,string QrID = "5hCTDArvncwhMHYtKdVSOqM")
    {
        //if (webCameraPanel.gameObject.activeInHierarchy)
        //{
        //    webCameraPanel.gameObject.SetActive(false);//如果
        //}
        StartCoroutine(GetQrTexture2D(Text, QrID, e =>
        {
            QrShowArea.SetActive(true);
            string URL = "https:" + e;
            QrShowArea.GetComponent<RawImage>().texture = e;
        }));
    }
}
